package com.jiuwan.gamepass.service.userImpl;

import cn.hutool.core.util.StrUtil;
import com.jiuwan.gamepass.dao.authDao.SysUserDao;
import com.jiuwan.gamepass.dto.authDto.Result;
import com.jiuwan.gamepass.pojo.authPojo.SysUser;
import com.jiuwan.gamepass.pojo.model.MyUserDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.thymeleaf.extras.springsecurity5.auth.AuthUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.List;


/**
 * @version 1.0
 * 功能目的描述 ：用于  重写UserDetailsService    ========>>>>>>>>>>>
 * @author： pang-yun
 * @date： 2021-06-22 17:00
 */


@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private SysUserDao sysUserDao;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        if (StrUtil.isEmpty(s)) {
            throw new RuntimeException("用户名不能为空");
        }
        //用户基础数据加载
        //如果不为空，则根据用户名获取用户信息
        SysUser sysUser = sysUserDao.selectByUsername(s);
        if (sysUser == null) {
            throw new UsernameNotFoundException(String.format("%s：此用户不存在", s));
        }
        MyUserDetails myUserDetails = new MyUserDetails();
        myUserDetails.setUsername(sysUser.getUsername());
        myUserDetails.setPassword(sysUser.getPassword());
        myUserDetails.setEnabled(true);


        //用户的角色查询
        String role = sysUserDao.selectRoleByUsername(s);
        //角色权限的标识， 前面需要加上ROLE_
        String roleStr = "ROLE_" + role;
        //根据用户的角色加载当前用户所具有的权限
        List<String> authorities = sysUserDao.selectApiUrlByRole(role);

        authorities.add(roleStr);
        myUserDetails.setAuthorities(AuthorityUtils.commaSeparatedStringToAuthorityList(
                String.join(",",authorities)
        ));

        return myUserDetails;
    }


}
